#include "usermanage.h"

bool usermanager::finduser(std::string ID, user *&ptr)
{
    for(int i = 0;i<users.size();i++)
    {
        bool result = users[i].ID == ID;
        if(result)
        {
            ptr = &users[i];
            return 1;
        }
    }
    return 0;
}

user* usermanager::newuser()
{
    user middle;
    middle.ID = std::to_string(users.size() + 100000);
    middle.level = normuser;
    users.emplace_back(middle);
    return &users[users.size() - 1];
}

void usermanager::loaddatabase(std::string location)
{
    std::fstream database(location);
    if(!database.is_open())
        return;
    databaselocation = location;
    int number = 0;
    database >> number;
    for(int i = 0;i<number;i++)
    {
        user middle;
        database >> middle.name;
        database >> middle.ID;
        database >> middle.points;
        int _middle = 0;
        database >> _middle;
        if(_middle == 0)
        {   
            middle.level = normuser;
        }
        else if(_middle == 0)
        {
            middle.level = vip;
        }
        else
        {
            middle.level = supervip; 
        }
        users.emplace_back(middle);
    }
}

void usermanager::unloaddatabase()    
{
    if(databaselocation.empty())
        return;
    std::fstream database(databaselocation);
    database << users.size() << "\n";
    for(user middle : users)
    {
        database << middle.name << " ";
        database << middle.ID << " ";
        database << middle.points << " ";
        int _middle;
        if(middle.level == normuser)
        {   
            _middle = 0;
        }
        else if(middle.level == vip)
        {
            _middle = 1;
        }
        else
        {
            _middle = 2; 
        }
        database << _middle << "\n";
    }
}